package cn.learn.validator.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 密码的校验
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2020年08月01日15:22
 */
public class PasswordValidator implements ConstraintValidator<Password, String> {
    /**
     * 包含数字,英文,字符中的两种以上，长度6-8
     */
    private final static Pattern PATTERN = Pattern.compile("^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{6,8}$");


    @Override
    public void initialize(Password constraintAnnotation) {

    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (s.isEmpty()) {
            setMessage(constraintValidatorContext, "密码不能为空");
            return false;
        } else if (s.length() < 6 || s.length() > 8) {
            setMessage(constraintValidatorContext, "密码位数不够");
            return false;
        }
        if (!PATTERN.matcher(s).matches()) {
            setMessage(constraintValidatorContext, "密码要包含数字,英文,字符");
            return false;
        }
        return true;
    }

    private void setMessage(ConstraintValidatorContext constraintValidatorContext, String msg) {
        //禁用默认的message的值
        constraintValidatorContext.disableDefaultConstraintViolation();
        //重新添加错误提示语句
        constraintValidatorContext.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
    }

}
